package com.example.guesswho.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.guesswho.ui.components.CountdownTimer
import com.example.guesswho.ui.components.PrimaryButton
import com.example.guesswho.ui.components.SecondaryButton
import com.example.guesswho.ui.theme.GuessWhoTheme
import kotlinx.coroutines.delay

data class RoomInfo(
    val id: String,
    val difficulty: Int,
    val playerCount: Int,
    val maxPlayers: Int = 6,
    val status: String = "waiting"
)

@Composable
fun MatchScreen(
    onMatchSuccess: (String) -> Unit,
    onBackClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    var isMatching by remember { mutableStateOf(false) }
    var countdownTime by remember { mutableStateOf(30) }
    var selectedDifficulty by remember { mutableStateOf(1) }
    var matchedRoom by remember { mutableStateOf<RoomInfo?>(null) }
    
    val sampleRooms = remember {
        listOf(
            RoomInfo("room1", 1, 2, 6, "waiting"),
            RoomInfo("room2", 2, 4, 6, "playing"),
            RoomInfo("room3", 1, 1, 6, "waiting"),
            RoomInfo("room4", 3, 5, 6, "waiting")
        )
    }

    LaunchedEffect(isMatching) {
        if (isMatching) {
            var timeLeft = 30
            while (timeLeft > 0 && isMatching) {
                delay(1000)
                timeLeft--
                countdownTime = timeLeft
                
                if (timeLeft == 15) {
                    matchedRoom = RoomInfo("matched_room_${System.currentTimeMillis()}", selectedDifficulty, 3, 6, "playing")
                    onMatchSuccess(matchedRoom!!.id)
                    isMatching = false
                    break
                }
            }
            
            if (timeLeft == 0) {
                isMatching = false
                countdownTime = 30
            }
        }
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background)
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            IconButton(onClick = onBackClick) {
                Icon(
                    imageVector = Icons.Default.ArrowBack,
                    contentDescription = "Back",
                    tint = MaterialTheme.colorScheme.onBackground
                )
            }
            
            Text(
                text = "匹配对战",
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onBackground
            )
            
            Spacer(modifier = Modifier.width(48.dp))
        }

        Spacer(modifier = Modifier.height(32.dp))

        if (isMatching) {
            MatchingContent(
                countdownTime = countdownTime,
                onCancelMatch = { isMatching = false }
            )
        } else {
            DifficultySelectionContent(
                selectedDifficulty = selectedDifficulty,
                onDifficultySelected = { selectedDifficulty = it },
                onStartMatch = { isMatching = true },
                availableRooms = sampleRooms
            )
        }
    }
}

@Composable
fun MatchingContent(
    countdownTime: Int,
    onCancelMatch: () -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        CircularProgressIndicator(
            modifier = Modifier.size(64.dp),
            color = MaterialTheme.colorScheme.primary,
            strokeWidth = 4.dp
        )
        
        Spacer(modifier = Modifier.height(32.dp))
        
        CountdownTimer(
            totalTime = 30,
            onTimeUp = { onCancelMatch() }
        )
        
        Spacer(modifier = Modifier.height(32.dp))
        
        Text(
            text = "正在匹配对手...",
            fontSize = 20.sp,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.onBackground
        )
        
        Text(
            text = "预计等待时间: ${countdownTime}秒",
            fontSize = 16.sp,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        
        Spacer(modifier = Modifier.height(48.dp))
        
        SecondaryButton(
            text = "取消匹配",
            onClick = onCancelMatch
        )
    }
}

@Composable
fun DifficultySelectionContent(
    selectedDifficulty: Int,
    onDifficultySelected: (Int) -> Unit,
    onStartMatch: () -> Unit,
    availableRooms: List<RoomInfo>,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(24.dp)
    ) {
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant
            )
        ) {
            Column(
                modifier = Modifier.padding(20.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Text(
                    text = "选择难度",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    DifficultyButton(
                        level = 1,
                        label = "简单",
                        selected = selectedDifficulty == 1,
                        onClick = { onDifficultySelected(1) }
                    )
                    DifficultyButton(
                        level = 2,
                        label = "中等",
                        selected = selectedDifficulty == 2,
                        onClick = { onDifficultySelected(2) }
                    )
                    DifficultyButton(
                        level = 3,
                        label = "困难",
                        selected = selectedDifficulty == 3,
                        onClick = { onDifficultySelected(3) }
                    )
                }
            }
        }
        
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant
            )
        ) {
            Column(
                modifier = Modifier.padding(20.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "可用房间",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Badge(
                        containerColor = MaterialTheme.colorScheme.primary
                    ) {
                        Text(text = "${availableRooms.size}")
                    }
                }
                
                LazyColumn(
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                    modifier = Modifier.height(200.dp)
                ) {
                    items(availableRooms) { room ->
                        RoomCard(room = room)
                    }
                }
            }
        }
        
        PrimaryButton(
            text = "开始匹配",
            onClick = onStartMatch
        )
    }
}

@Composable
fun DifficultyButton(
    level: Int,
    label: String,
    selected: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    OutlinedButton(
        onClick = onClick,
        modifier = modifier.weight(1f),
        colors = ButtonDefaults.outlinedButtonColors(
            containerColor = if (selected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent,
            contentColor = if (selected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.primary
        )
    ) {
        Text(
            text = label,
            fontSize = 16.sp,
            fontWeight = FontWeight.Medium
        )
    }
}

@Composable
fun RoomCard(
    room: RoomInfo,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surface
        )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column {
                Text(
                    text = "房间 ${room.difficulty}星",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    color = MaterialTheme.colorScheme.onSurface
                )
                Text(
                    text = "${room.playerCount}/${room.maxPlayers} 人",
                    fontSize = 14.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            
            Badge(
                containerColor = when (room.status) {
                    "waiting" -> MaterialTheme.colorScheme.primary
                    "playing" -> MaterialTheme.colorScheme.tertiary
                    else -> MaterialTheme.colorScheme.surfaceVariant
                }
            ) {
                Text(
                    text = when (room.status) {
                        "waiting" -> "等待中"
                        "playing" -> "游戏中"
                        else -> "已结束"
                    }
                )
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun MatchScreenPreview() {
    GuessWhoTheme {
        MatchScreen(
            onMatchSuccess = {},
            onBackClick = {}
        )
    }
}